package com.lyl.controller;

import com.lyl.geetest.GeetestLib;
import com.lyl.geetest.GeetestLibResult;
import com.lyl.model.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author lylbell
 * @date 2021-06-28 16:18
 */
@RequestMapping("/gt")
@RestController
@Api(tags = "极验验证的数据接口")
public class GeetsetController {

    @Autowired
    private GeetestLib geetestLib;

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    @GetMapping("/register")
    @ApiOperation("极验验证获取第一次数据包---注册")
    @ApiImplicitParam(name = "uuid",value = "用户的标识")
    public Result<String> register(String uuid) {
        String digestmod = "md5";

        //构造极验数据包
        Map<String,String> paramMap = new HashMap<String, String>();
        paramMap.put("digestmod", digestmod);
        paramMap.put("user_id", uuid);
        paramMap.put("client_type", "web");
//        paramMap.put("ip_address", "127.0.0.1");
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
        paramMap.put("ip_address", requestAttributes.getRequest().getRemoteAddr());
        //极验验证返回的结果
        GeetestLibResult result = geetestLib.register(digestmod, paramMap);
        // 将结果状态写到redis中，此处register接口存入redis，后续validate接口会取出使用
        redisTemplate.opsForValue().set(GeetestLib.GEETEST_SERVER_STATUS_SESSION_KEY+":"+uuid,result.getStatus(),180, TimeUnit.SECONDS);
        redisTemplate.opsForValue().set(GeetestLib.GEETEST_SERVER_USER_KEY+":"+uuid,uuid,180,TimeUnit.SECONDS);
        // 注意，不要更改返回的结构和值类型
        return Result.ok(result.getData());
    }
}
